const { default: axios } = require('axios')
const { lackContent } = require('../constant/filetypeError')
const { musicInfoExist } = require('../constant/musiclikeErrortype')
const FormData = require('form-data')
const { token } = require('../config/config_deafault')
const artileVAild = async (ctx, next) => {

    const { content } = ctx.request.body
    if (!content) {
        return ctx.app.emit('error', lackContent, ctx)
    }
    await next()
}

const UploadFileControlle = async (ctx, next) => {
    if (ctx.request.files.length > 6)
        return ctx.app.emit('error', musicInfoExist, ctx)
    try {
        if (ctx.request.files.length > 0) {

            const contentImage = []
            //使用异步操作并发提升上传
            const uploadList = ctx.request.files.map((files) => {
                const formData = new FormData()
                formData.append('file', files.buffer, files.originalname)

                return axios.post(`http://skypro.afterglow26.cn:28080/api/v1/upload`, formData, {
                    headers: {
                        Authorization: token,
                        "Content-Type": "multipart/form-data"
                    },
                    timeout: 100000
                }).then((res) => {
                    if (res.data.status == true) {
                        let imagekey = res.data.data.key
                        let image = res.data.data.links.url
                        return { image, imagekey }
                    } else {
                        throw new Error("上传失败");
                    }
                })
            })
            // 等待所有上传请求完成
            const results = await Promise.all(uploadList);
            // 将所有成功的上传结果添加到 contentImage
            contentImage.push(...results);
            ctx.request.body.contentImage = contentImage;
            await next()
        }


    } catch (error) {
        console.log(error);
    }
}

module.exports = {
    artileVAild,
    UploadFileControlle
}